package com.zlst.uimp.cas;

import com.google.common.collect.Multimap;
import com.zlst.uimp.cas.authentication.UimpAuthenticationHandler;

import org.apache.commons.lang.StringUtils;
import org.apereo.cas.authentication.AuthenticationEventExecutionPlan;
import org.apereo.cas.authentication.AuthenticationEventExecutionPlanConfigurer;
import org.apereo.cas.authentication.AuthenticationHandler;
import org.apereo.cas.authentication.CoreAuthenticationUtils;
import org.apereo.cas.authentication.principal.DefaultPrincipalFactory;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.authentication.principal.PrincipalNameTransformerUtils;
import org.apereo.cas.authentication.support.password.PasswordEncoderUtils;
import org.apereo.cas.authentication.support.password.PasswordPolicyConfiguration;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.support.JpaBeans;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

/**
 * 注册认证handler
 * Created by 170121 on 2018/6/8.
 */
@Configuration("UimpAuthenticationEventExecutionPlanConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class UimpAuthenticationEventExecutionPlanConfiguration implements AuthenticationEventExecutionPlanConfigurer {


    @Autowired
    private CasUimpAuthenticationProperties casUimpAuthenticationProperties;

    @Autowired
    @Qualifier(value = "servicesManager")
    private ServicesManager servicesManager;

    @Override
    public void configureAuthenticationExecutionPlan(AuthenticationEventExecutionPlan plan) {
            plan.registerAuthenticationHandler(uimpAuthenticationHandler());
    }

    @Bean("sakilaDataSource")
    @ConfigurationProperties(value = "cas.uimp.authn.jdbc.encode")
    public CasUimpAuthenticationProperties casUimpAuthenticationProperties() {
        return new CasUimpAuthenticationProperties();
    }

    @Bean
    public UimpAuthenticationHandler uimpAuthenticationHandler() {
        System.out.print("============初始化UimpAuthenticationHandler===============start");
        try{
        CasUimpAuthenticationProperties c = casUimpAuthenticationProperties;
        DataSource datasource = JpaBeans.newDataSource(c);
        Multimap attributes = CoreAuthenticationUtils.transformPrincipalAttributesListIntoMultiMap(c.getPrincipalAttributeList());

        final UimpAuthenticationHandler handler =
            new UimpAuthenticationHandler(c.getName(), servicesManager, jdbcPrincipalFactory(), c.getOrder(),
                                          datasource, c.getAlgorithmName(), c.getSql(),
                                          c.getPasswordFieldName(), c.getSaltFieldName(), c.getExpiredFieldName(),
                                          c.getDisabledFieldName(), c.getNumberOfIterationsFieldName(), c.getNumberOfIterations(), c.getStaticSalt(), CollectionUtils.wrap(attributes));
        handler.setPasswordEncoder(PasswordEncoderUtils.newPasswordEncoder(c.getPasswordEncoder()));
        handler.setPrincipalNameTransformer(PrincipalNameTransformerUtils.newPrincipalNameTransformer(c.getPrincipalTransformation()));

//        if (queryAndEncodePasswordPolicyConfiguration != null) {
//            handler.setPasswordPolicyConfiguration(queryAndEncodePasswordPolicyConfiguration);
//        }

        handler.setPrincipalNameTransformer(PrincipalNameTransformerUtils.newPrincipalNameTransformer(c.getPrincipalTransformation()));

        if (StringUtils.isNotBlank(c.getCredentialCriteria())) {
            handler.setCredentialSelectionPredicate(CoreAuthenticationUtils.newCredentialSelectionPredicate(c.getCredentialCriteria()));
        }
            return handler;
        }catch(Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @ConditionalOnMissingBean(name = "jdbcPrincipalFactory")
    @Bean
    @RefreshScope
    public PrincipalFactory jdbcPrincipalFactory() {
        return new DefaultPrincipalFactory();
    }
}
